package com.bw.module_motorcircle.ui

import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.Router
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.BaseViewModel
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.uiLoader.UILoader
import com.bw.lib_common.uiLoader.UIState
import com.bw.lib_common.utils.ToastUtils
import com.bw.module_motorcircle.R
import com.bw.module_motorcircle.databinding.FragmentMotorCircleBinding
import com.bw.module_motorcircle.databinding.LayoutCustomTabViewBinding
import com.bw.module_motorcircle.helper.SeriesPopupMenuRvHelper
import com.bw.module_motorcircle.model.MotoCircleNavigationItem
import com.bw.module_motorcircle.ui.information.InformationFragment
import com.bw.module_motorcircle.ui.post.PostListFragment
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.launch

/**
 * 玩车模块
 * 1：UI状态组件封装
 * 2：viewpager2和fragment切换
 *
 *
 *
 */
@Route(path = Router.Ui.MotorCircleFragment)
@AndroidEntryPoint
class MotorCircleFragment : BaseFragment<MotorCircleViewModel,FragmentMotorCircleBinding>(){
    override val mLayoutResId: Int
        get() = R.layout.fragment_motor_circle
    private lateinit var mUiLoader:UILoader
    private var mViewPagerAdapter:MotoCircleViewPagerAdapter? = null
    private var mMediator:TabLayoutMediator? = null

    private val popupMenuRvHelper by lazy {
        SeriesPopupMenuRvHelper(layoutInflater) { navigationId, modelItem ->
            //修改数据源
            ToastUtils.showShort(requireActivity(),"点击了${modelItem.name}")
            val clickNavigation = mViewModel.mNavigationItem.find { it.navigationId == navigationId }
            clickNavigation?.modelList!!.forEach {
                it.checked = modelItem.modelId == it.modelId
            }
            mViewPagerAdapter?.notifyDataSetChanged()

        }
    }


    private val mViewModel:MotorCircleViewModel by viewModels()
    override fun initView() {
        super.initView()
        initUILoader()
        //测试UILoader
//        Thread{
//            Thread.sleep(2000)
//            mUiLoader.updateState(UIState.LOADING)
//            Thread.sleep(2000)
//            mUiLoader.updateState(UIState.UN_LOGIN)
//            Thread.sleep(2000)
//            mUiLoader.updateState(UIState.SUCCESS)
//
//        }.start()
    }

    override fun initData() {
        super.initData()
        mViewModel.getFixedNavigationItem()
    }

    override fun initListener() {
        super.initListener()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){//只有当前页面活跃的时候才订阅流数据，如果不些，页面关闭后还会订阅数据，导致内存泄露
                mViewModel.navigationState.collect{
                    when (it) {
                        is RequestEvent.Success -> {
                            handleNavigationData()
                            mUiLoader.updateState(UIState.SUCCESS)
                        }
                        is RequestEvent.Empty -> {
                            mUiLoader.updateState(UIState.EMPTY)
                        }

                        is RequestEvent.Error -> {
                            mUiLoader.updateState(UIState.NETWORK_ERROR)
                        }
                        is RequestEvent.Loading -> {
                            mUiLoader.updateState(UIState.LOADING)
                        }
                        else -> {}

                    }
                }

            }
        }
    }

    fun initUILoader(){
        mUiLoader = object :UILoader(requireContext()){
            override fun loadSuccessView(container: ViewGroup?): View? {
                return View(requireContext())
            }
        }
        mBinding.lContainer.addView(mUiLoader)

    }
    /**
     * 加载tab数据以及viewpager
     */
    private fun handleNavigationData() {
        initViewPager()
    }

    private fun initViewPager(){
        mViewPagerAdapter = MotoCircleViewPagerAdapter(mViewModel.mNavigationItem,this)
        mBinding.vp.adapter = mViewPagerAdapter
        //默认选中
        val default = mViewModel.mNavigationItem.find { it.defaultStatus == 1 } //默认被选中的
        val position = if (default == null) 0 else mViewModel.mNavigationItem.indexOf(default)
        mBinding.vp.currentItem = position
        mBinding.vp.offscreenPageLimit = 1
        //viewpager和tablayout联动
        mMediator = TabLayoutMediator(
            mBinding.tabLayout,
            mBinding.vp
        ){tab,position->
//            tab.text = mViewModel.mNavigationItem[position].title
            //自定义
            val tabView = DataBindingUtil.inflate<LayoutCustomTabViewBinding>(
                layoutInflater,
                R.layout.layout_custom_tab_view,
                null,
                false
            )
            if (position >= mViewModel.mNavigationItem.size) {
                return@TabLayoutMediator
            }
            val navigation = mViewModel.mNavigationItem[position]
            //判断二级目录，是否选中
            if (navigation.modelList == null || !navigation.modelList.any { it.checked }) {
                tabView.tab.text = navigation.title
            } else {
                tabView.tab.text = navigation.modelList.find { it.checked }?.name
            }
            tabView.ivArrow.visibility = if (navigation.modelList == null) View.GONE else View.VISIBLE
            //点击事件处理
            tabView.lTab.setOnClickListener {
                if (tab.isSelected){//选中，展开二级目录
                    if (navigation.modelList != null) {
                        showPopupList(tabView.lTab, navigation)
                    }
                }else{//未选中--》选中，展开二级目录
                    tab.select()
                    if (navigation.modelList != null) {
                        Handler(Looper.getMainLooper()).postDelayed({
                            showPopupList(
                                tabView.lTab,
                                navigation
                            )
                        }, 400)
                    }
                }
            }

            //设置自定义布局
            tab.customView = tabView.root

        }
        mMediator?.attach()
    }

    override fun onDestroy() {
        super.onDestroy()
        mMediator?.detach()
        mMediator = null
    }
    /**
     * 弹出二级目录
     */
    private fun showPopupList(lTab: ConstraintLayout, navigation: MotoCircleNavigationItem) {
        popupMenuRvHelper.bindItems(navigation.navigationId, navigation.modelList!!)
        popupMenuRvHelper.show(lTab)
    }


    inner class MotoCircleViewPagerAdapter(private val item:List<MotoCircleNavigationItem>,fa:Fragment):FragmentStateAdapter(fa){
        override fun getItemCount(): Int {
           return item.size
        }

        override fun createFragment(p0: Int): Fragment {
            return when(item[p0].type){
                1 -> {
                    val modelItem = item[p0].modelList.find { it.checked }
                    if (modelItem == null){
                        PostListFragment.newInstance(sortBy = "hot") //二级没选中，热门
                    }else{
                        PostListFragment.newInstance(sortBy = "hot") //二级被选中,再次区别
                    }
                }
                2 -> PostListFragment.newInstance(sortBy = "new")
                3 -> InformationFragment()
                4 -> PostListFragment.newInstance(ifFocus = 1)
                else -> PostListFragment()
            }
        }

    }

}